<!doctype html>
<html lang="en">
<head>
    <?php require_once "../include/header.php" ?>
    <style type="text/css">
        .todo:first-of-type {
            margin-top: 10px;
        }

        .todo {
            border: solid lightgray 1px;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 10px;

        }
        .todo:focus {
            background-color: lightgreen;
        }

        .hour, .money {
            width: 40px;
        }

        .timer {
            width: 100px;
        }

        .action {
            width: 30px;
            border: none;
        }

        .action-new {
            background-color: greenyellow;
        }

        .action-mod {
            background-color: orange;
        }

        .complete {
            text-decoration: line-through;
        }
        .complete-date{
            display: inline-block;
            margin-right: 10px;
            border: solid orange 1px;
            background-color: orange;
            color: #FFFFFF;
            line-height: 12px;
            font-size: 9px;
            font-weight: bold;
        }
    </style>
    <script>
        var Keys = {
            BACKSPACE : 8,
            TAB : 9,
            ENTER : 13,
            ESC : 27,
            SPACE : 32,
            LEFT : 37,
            UP : 38,
            RIGHT : 39,
            DOWN : 40,
            DELETE : 46,
            ONE: 49,
            NINE: 57,
            B:66, //blog
            D:68, //edit mode
            I:73, //edit mode
            J:74, //up
            K:75, //down
            M:77, //mark as complete
            N:78,  //new
            W:87
        };
        var datePicker = null;

        function newMode(){
            $('#action').val('new').removeClass('action-mod').addClass('action-new');
            $("#id").val(-1);
            $("#hr").val(0);
            $("#min").val(0);
            $("#duration").val(0);
            $("#expense").val(0);
            $("#appear_after").val('');
            $("#priority").val(1);
            $("#content").val('').focus();
            window.scrollTo(0,0);
        }
        function editMode(){
            var $this = $(".todo:focus");
            var rowId = $this.data('id');
            var duration = parseInt($this.data('duration'));
            var expense = $this.data('expense');
            var appearAfter = $this.data('appear-after');
            var priority = $this.data('priority');

            $("#action").val('mod').removeClass('action-new').addClass('action-mod');
            $("#id").val(rowId);
            $("#duration").val(duration);
            if (duration > 0) {
                $("#hr").val(Math.floor(duration / 60));
                $("#min").val(duration % 60);
            } else {
                $("#hr").val(0);
                $("#min").val(0);
            }
            $("#expense").val(expense);

            if(appearAfter){
                appearAfter = appearAfter.substring(0,10);
                $('#appear_after').datepicker( "setDate" , appearAfter );
            }else{
                $('#appear_after').datepicker( "setDate" , null );
            }

            $("#priority").val(priority);
            $("#content").focus();
            $("#content").val($this.find(".todo-text").html().replace(/<br>/g, '\n'));
            window.scrollTo(0, 0);
        }

        function viewMode(){
            newMode();
            $(".todo:visible:first").focus();
        }

        function nextVisible(){
            var $cur = $(".todo:focus");
            var $next = $cur.next();
            if($next.size() == 0){
                return $next;
            } else{
                while($next.size() > 0 && !$next.is(":visible")){
                    $next = $next.next();
                }
                return $next;
            }
        }
        function prevVisible(){
            var $cur = $(".todo:focus");
            var $prev = $cur.prev();
            if($prev.size() == 0){
                //already the first, scroll 00
                window.scrollTo(0,0);
                return $prev;
            } else{
                while($prev.size() > 0 && !$prev.is(":visible")){
                    $prev = $prev.prev();
                }
                return $prev;
            }
        }

        function markComplete() {
            if (confirm("mark as complete?")) {
                var $this = $(".todo:focus");
                var rowId = $this.data('id');
                $.ajax({
                    url: 'todo_action.php?action=mc&id=' + rowId,
                    success: function () {
                        var $target = nextVisible();
                        if($target.size() == 0){
                            $target = prevVisible();
                        }
                        $this.hide();
                        //$(".todo:visible:first").focus();
                        $target.focus();

                    },
                    error: function () {
                        console.log('error');
                    }
                });
            }
        }

        function deleteTodo() {
            if (confirm("delete ?")) {
                var $this = $(".todo:focus");
                var rowId = $this.data('id');
                $.ajax({
                    url: 'todo_action.php?action=del&id=' + rowId,
                    success: function () {
                        var $target = nextVisible();
                        if($target.size() == 0){
                            $target = prevVisible();
                        }

                        $this.hide();
                        //$(".todo:visible:first").focus();
                        $target.focus();
                    },
                    error: function () {
                        console.log('error');
                    }
                });
            }
        }


        $(document).ready(function () {
            newMode();
            $("#appear_after").datepicker({dateFormat: 'yy-mm-dd'});

            $('#action').bind('dblclick', function () {
                newMode();
            });

            $('.todo').bind('dblclick', function () {
                markComplete();
            });

            $(document).bind('keyup',function(e){
                if (e.ctrlKey) {
                    var n = parseInt(e.keyCode) - 48;
                    console.log("n:", n);
                    if(n>0 && n < 10){
                        $(".todo:visible:nth-of-type("+ n +")").focus();
                    } else if(e.keyCode == Keys.W){
                        window.close();
                    }
                } else if(e.keyCode == Keys.ESC){
                    viewMode();
                }
            });

            $(".todo").bind('keydown',function(e){
                console.log(e.keyCode);

                if(e.keyCode == Keys.DOWN || e.keyCode == Keys.J){
                    nextVisible().focus();
                } else if(e.keyCode == Keys.UP || e.keyCode == Keys.K){
                    prevVisible().focus();
                } else if(e.keyCode == Keys.I){
                    e.preventDefault();
                    editMode();

                } else if(e.keyCode == Keys.M){
                    markComplete();
                } else if(e.keyCode == Keys.N){

                    e.preventDefault();
                    newMode();
                } else if(e.keyCode == Keys.DELETE || e.keyCode == Keys.D){
                    deleteTodo();
                } else if(e.keyCode == Keys.B){
                    window.location='../index.php';
                }

                //e.preventDefault();
            });

            $('#content').bind("keyup", function (e) {
                e.preventDefault();
                if (e.ctrlKey && e.keyCode == 13) { //b
                    if ($('#action').val() == 'mod') {
                        if (!confirm('are u sure to modify?')){
                            return false;
                        }
                    }

                    var hr = $('#hr').val();
                    if (hr == '') {
                        hr = 0;
                    }
                    var min = $("#min").val();
                    if (min == '') {
                        min = 0;
                    }

                    $("#duration").val(parseInt(hr * 60) + parseInt(min));
                    console.log("duration:", $("#duration").val());
                    $("#todoForm").submit();
                }
            })
        });
    </script>
</head>
<body>
<div class="container">
    <?php
    require_once('../include/conn.php');
    $limit = $_GET["limit"];

    $result = null;
    if($limit != "all"){
        $limit = "select * from todo where status='new' and (appear_after is null or appear_after<=now()) ";
        $limit .= " union all select * from todo where status='complete' and date(complete_date) = date(now()) order by status desc, complete_date desc";
    } else {
        $limit = "select * from todo order by status desc, complete_date desc";
    }

    $result = mysql_query( $limit);

    if (!$result) {
        echo "db error:" . mysql_error() . "<br>" . $limit;
        echo "<section>
            Please <a href='setup.php'> setup database</a> first.<br>
        </section>";
    } else {
        ?>
        <form id="todoForm" method="post" action="todo_action.php">
            <div>
                <textarea name="content" id="content" cols="120" rows="5"></textarea>
            </div>
            <div>
                <input name="action" id="action" readonly type="text" class="action new" value="new" size="3"/>
                <input name="id" id="id" type="hidden" value="-1"/>
                -

                <input class="hour" type="number" min="0" max="24" name="hr" id="hr" value="0"/>'
                <input class="hour" type="number" min="0" max="59" name="min" id="min" value="0"/>''
                <input name="duration" id="duration" type="hidden" value="0"/>
                ,￥<input class="money" type="number" name="expense" id="expense" min="0" max="10000"/>
                ,T<input class="timer" type="text" name="appear_after" id="appear_after"/>
                , <input class="hour" type="number" name="priority" id="priority" value="1" min="0" max="2"/>

            </div>

            <div style="display: none">
                <input type="submit" value="Submit"/>
            </div>

        </form>


        <div id="todoTable">
            <?php
            $tabindex = 10;
            $order = array("\r\n", "\n", "\r");
            $replace = '<br>';
            while ($row = mysql_fetch_array($result)) {
                echo "<div class='todo' tabindex=" . $tabindex ." data-id=" . $row['id'] . " data-duration=" . $row['duration'] . " data-expense=" . $row['expense'] . " data-appear-after='" . $row['appear_after'] . "' data-priority='" . $row['priority'] . "'>";
                if($row['status'] == 'complete'){
                    echo "<span class='complete-date'>". substr($row['complete_date'],5,11) . "</span>";
                }
                echo "<span class='todo-text " . $row['status'] . "'>" . str_replace($order, $replace, $row['content']). "</span>";
                echo "</div>";
                $tabindex++;
            }
            ?>
        </div>
    <?php
    }
    ?>
</div>
</body>
</html>

<?php
mysql_close($conn);
?>